/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package outToR;

import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import units.CellType;
import units.DifferentialExpression;
import units.DifferentialExpressionLibrary;
import units.GeneLibrary;
import units.MonkeyType;
import utils.FileUtils;
import utils.Handle;

/**
 *
 * @author jamie
 */
public class TogetherClustOutput {

    private Integer[] timePoints = {1, 14, 28, 65};
    private boolean useCellTypeL = true;
    private File outputFile = new File("/Users/jamie/Dropbox/monkeys/outputForR/clust/allTogether_PL_POST.txt");
    private File outputFile_isgsOnly = new File("/Users/jamie/Dropbox/monkeys/outputForR/clust/allTogether_PL_POST_isgsOnly.txt");
    private boolean isgsOnly = true;
//    private Integer[] timePoints = {1, 14, 28, 65};
//    private boolean useCellTypeL = true;
//    private File outputFile = new File("/Users/jamie/monkeys/outputForR/clust/allTogether_PL_POST.txt");
    private DifferentialExpressionLibrary del;
    private double maxP = 0.1;

    public TogetherClustOutput() {
        GeneLibrary library = new GeneLibrary();

        del = new DifferentialExpressionLibrary();
        del.populateForAllMonkeyTypes(library);
        library.populateGeneSymbols();

    }

    public void makeOutput() {
        BufferedWriter writer;
        if(!isgsOnly){
            writer = FileUtils.getBufferedWriter(outputFile);
        } else {
            writer = FileUtils.getBufferedWriter(outputFile_isgsOnly);
        }
        if (useCellTypeL) {
            for (MonkeyType mt : MonkeyType.values()) {
                for (CellType ct : CellType.values()) {
                    try {
                        makeClustOutput(mt, ct, writer);
                    } catch (IOException ex) {
                        Logger.getLogger(TogetherClustOutput.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        } else {
            for (MonkeyType mt : MonkeyType.values()) {
                try {
                    makeClustOutput(mt, CellType.P, writer);
                } catch (IOException ex) {
                    Logger.getLogger(TogetherClustOutput.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        try {
            writer.close();
        } catch (IOException ex) {
            Logger.getLogger(TogetherClustOutput.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void makeClustOutput(MonkeyType mt, CellType ct, BufferedWriter writer) throws IOException {
        List<Integer> isgs = null;
        if (isgsOnly) {
            isgs = getISGs(mt, ct);
        }
        TreeMap<Integer, List<DifferentialExpression>> deGenes = del.getDifferentialExpressedGenes(mt, ct, timePoints, maxP);
        for (int probeId : deGenes.keySet()) {
            boolean include = true;
            if (isgsOnly) {
                if (!isgs.contains(probeId)) {
                    include = false;
                }
            }
            
            if (include) {
                StringBuffer valuesBuffer = new StringBuffer();

//            System.out.println(g.getSymbol());

                valuesBuffer.append(mt.name() + ct.name() + "_" + probeId + "\t0.0\t");
                for (int timePoint : timePoints) {


                    for (DifferentialExpression de : deGenes.get(probeId)) {
                        if (de.getTimePoint() == timePoint && de.getCellType().equals(ct)) {

                            valuesBuffer.append(de.getLogExp() + "\t");

                        }
                    }

                }
                writer.append(valuesBuffer.toString().trim() + "\n");
            }
        }

    }

    private List<Integer> getISGs(MonkeyType mt, CellType ct) {
        Handle handle = Handle.getConnectedHandle("monkeys");
        String sql;
        sql = "select distinct t2.probeId from hcv.isgs t1, expression t2, sample t3 where t2.gId=t1.gId and t3.id=t2.sampleId and t3.monkeyType='" + mt.name() + "' and t3.cellType='" + ct.name() + "'";
        ResultSet rs = handle.runSQLquery(sql);
        List<Integer> ids = new ArrayList<Integer>();
        try {
            while (rs.next()) {
                ids.add(rs.getInt("probeId"));
            }
            rs.close();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        handle.closeConnection();
        return ids;
    }
}
